import argparse
import logging
import os

import numpy as np
import torch
import torch.nn.functional as F
from torchvision import transforms

from utils.data_loading import BasicDataset
from models.unet import UNet
from PIL import Image
import cv2
import shapely.geometry


def unet_predict_img(net,
                     full_img,
                     device,
                     scale_factor=1,
                     out_threshold=0.5):
    net.eval()
    img = torch.from_numpy(BasicDataset.preprocess(full_img, scale_factor, is_mask=False))
    img = img.unsqueeze(0)
    img = img.to(device=device, dtype=torch.float32)

    with torch.no_grad():
        output = net(img)

        if net.n_classes > 1:
            probs = F.softmax(output, dim=1)[0]
        else:
            probs = torch.sigmoid(output)[0]

        tf = transforms.Compose([
            transforms.ToPILImage(),
            transforms.Resize((full_img.size[1], full_img.size[0])),
            transforms.ToTensor()
        ])

        full_mask = tf(probs.cpu()).squeeze()

    if net.n_classes == 1:
        return (full_mask > out_threshold).numpy()
    else:
        return F.one_hot(full_mask.argmax(dim=0), net.n_classes).permute(2, 0, 1).numpy()


def get_args():
    parser = argparse.ArgumentParser(description='Predict masks from input images')
    parser.add_argument('--model', '-m', default='./front-segment-model-v1.pth', metavar='FILE',
                        help='Specify the file in which the model is stored')
    parser.add_argument('--input', '-i', metavar='INPUT', nargs='+', help='Filenames of input images', required=True)
    parser.add_argument('--output', '-o', default='./predicted.png', metavar='INPUT', nargs='+',
                        help='Filenames of output images')
    parser.add_argument('--viz', '-v', action='store_true',
                        help='Visualize the images as they are processed')
    parser.add_argument('--no-save', '-n', action='store_true', help='Do not save the output masks')
    parser.add_argument('--mask-threshold', '-t', type=float, default=0.5,
                        help='Minimum probability value to consider a mask pixel white')
    parser.add_argument('--scale', '-s', type=float, default=0.5,
                        help='Scale factor for the input images')

    return parser.parse_args()


def get_output_filenames(args):
    def _generate_name(fn):
        split = os.path.splitext(fn)
        return f'{split[0]}_OUT{split[1]}'

    return args.output or list(map(_generate_name, args.input))


def mask_to_image(mask: np.ndarray):
    if mask.ndim == 2:
        return Image.fromarray((mask * 255).astype(np.uint8))
    elif mask.ndim == 3:
        return Image.fromarray((np.argmax(mask, axis=0) * 255 / mask.shape[0]).astype(np.uint8))


def getContours(image, save_thresh=False):
    image = image.astype(np.uint8)
    ret, thresh = cv2.threshold(image, 30, 255, cv2.THRESH_BINARY)
    if save_thresh:
        cv2.imwrite('./thresh_view.jpg', thresh)
    contours, hierachy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    areas = [cv2.contourArea(cnt) for cnt in contours]
    return contours, areas


def getMask(filename):
    img = Image.open(filename)
    mask = unet_predict_img(net=net, full_img=img, device=device, scale_factor=args.scale,
                            out_threshold=args.mask_threshold)
    return mask


def lost_defect_detect(body_areas, face_areas, results):
    lip_area = max(body_areas) + max(face_areas)
    print(f'lipstic area:{lip_area}')
    # todo
    lost_defect = {}
    if lip_area < 375900 / 16:
        results["all-lost"] = 1
        # lost_defect['all-lost'] = 1
    elif lip_area < 375900 / 2:
        # lost_defect['half-lost'] = 1
        results["half-lost"] = 1
    return results


def box_selectby_semantics(i, box, body_cnt, face_cnt, bottom_cnt, del_list, show_choice, temp_cls, temp_conf, opt):
    # box_mask = ground[box[0] - box[2]/2:box[0] + box[2]/2, box[1] - box[3]/2, box[1] + box[3]/2]
    # ground = np.zeros(2024, 2048)
    box_center = shapely.geometry.Point(box[0], box[1])  # 需要时标记框中心坐标
    body_cnt = np.reshape(body_cnt, (1, 1, body_cnt.shape[0], 2)).tolist()
    face_cnt = np.reshape(face_cnt, (1, 1, face_cnt.shape[0], 2)).tolist()
    bottom_cnt = np.reshape(bottom_cnt, (1, 1, bottom_cnt.shape[0], 2)).tolist()

    # box_context
    body_context = {'type': 'MULTIPOLYGON',
                    'coordinates': body_cnt}
    face_context = {'type': 'MULTIPOLYGON',
                    'coordinates': face_cnt}
    bottom_context = {'type': 'MULTIPOLYGON',
                      'coordinates': bottom_cnt}

    # body_shape
    body_shape = shapely.geometry.shape(body_context)
    face_shape = shapely.geometry.shape(face_context)
    bottom_shape = shapely.geometry.shape(bottom_context)

    # todo  多选
    if body_shape.intersects(box_center):
        print('in body')
        if not show_choice["body"]:
            del_list.append(i)
        else:
            if temp_conf < opt["body_conf_thres"][temp_cls]:
                del_list.append(i)
    elif face_shape.intersects(box_center):
        print('in face')
        if not show_choice["face"]:
            del_list.append(i)
        else:
            if temp_conf < opt["face_conf_thres"][temp_cls]:
                del_list.append(i)
    elif bottom_shape.intersects(box_center):
        print('in bottom')
        if not show_choice["bottom"]:
            del_list.append(i)
        else:
            if temp_conf < opt["bottom_conf_thres"][temp_cls]:
                del_list.append(i)
    else:
        print('in background')
        del_list.append(i)
    return del_list


if __name__ == '__main__':
    args = get_args()
    in_files = args.input
    out_files = get_output_filenames(args)

    net = UNet(n_channels=3, n_classes=4)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    logging.info(f'Loading model {args.model}')
    logging.info(f'Using device {device}')

    net.to(device=device)
    net.load_state_dict(torch.load(args.model, map_location=device))

    logging.info('Model loaded!')

    img = Image.open(in_files)
    # 调用模型
    mask = unet_predict_img(net=net, full_img=img, device=device, scale_factor=args.scale,
                            out_threshold=args.mask_threshold)

    background, bottom = mask[0, :, :] * 50, mask[1, :, :] * 50
    body, face = mask[2, :, :] * 50, mask[3, :, :] * 50

    # cv2.imwrite('./background.jpg', background)
    # cv2.imwrite('./bottom.jpg', bottom)
    # cv2.imwrite('./body.jpg', body)
    # cv2.imwrite('./face.jpg', face)
    body_contours, body_areas = getContours(body)
    face_contours, face_areas = getContours(face)
    bottom_contours, bottom_areas = getContours(bottom)

    # 检测断裂缺陷--新类型缺陷,与之前的并列
    lost_defect_detect(body_areas, face_areas)

    # 根据unet删选yolo的输出结果
    box_selectby_semantics([857, 407, 100, 100], body_contours[0], face_contours[0], bottom_contours[0])
